//
//  LoopHomeRefreshView.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/15.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

private let refreshHeight:CGFloat = 60

enum RefreshState:Int {
    case Normal = 0
    case Already
    case Refresh
}
class LoopHomeRefreshView: UIControl {
    
    var scollerState:RefreshState = .Normal{
        didSet{
            switch scollerState {
            case .Normal:
//                print("normal")
                lblTip.text = "再拉我要报警了"
                activityView.stopAnimating()
                arrow.isHidden = false
                //将箭头状态修改回来
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrow.transform = CGAffineTransform.identity
                })
                
                //不加判断,UI布局会出错
                if oldValue == .Refresh{
                
                    UIView.animate(withDuration: 0.25, animations: {
                        self.scorllView!.contentInset.top = self.scorllView!.contentInset.top - refreshHeight
                    })
                }
                
            case .Already:
//                print("already")
                lblTip.text = "别拉我,我要飞"
                //让箭头旋转
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrow.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                
            case .Refresh:
//                print("refresh")
                lblTip.text = "o~~~要出来了"
                activityView.startAnimating()
                arrow.isHidden = true
                //发送刷新消息
                sendActions(for: .valueChanged)
                //修改scorllView,制造出悬停效果
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scorllView!.contentInset.top = self.scorllView!.contentInset.top + refreshHeight
                })
                
            }
        
        }
    
    }
    
    func endRefreshing(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            
            self.scollerState = .Normal
        }

    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: screenWidth, height: refreshHeight)

        super.init(frame: rect)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加视图的时候会调用这个方法
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView{
            scorllView = fatherView
            scorllView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    //KVO的处理方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let currentOffset = scorllView?.contentOffset.y ?? 0
        let targetOffset = -(scorllView!.contentInset.top + refreshHeight)

        if scorllView!.isDragging{
        
            if scollerState == .Normal && currentOffset < targetOffset {
                scollerState = .Already
            }else if scollerState == .Already && currentOffset > targetOffset{
                scollerState = .Normal
            }
            
        }else{
            if scollerState == .Already {
                scollerState = .Refresh
            }
        }
    }
    
    func setupUI(){
    
        //添加控件
        addSubview(bgImage)
        addSubview(arrow)
        addSubview(lblTip)
        addSubview(activityView)
        
        //添加约束
        bgImage.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        
        arrow.snp.makeConstraints { (make) in
            make.right.equalTo(lblTip.snp.left).offset(-8)
            make.centerY.equalTo(lblTip.snp.centerY)
            make.height.width.equalTo(32)
        }
        
        lblTip.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-8)
        }
        
        activityView.snp.makeConstraints { (make) in
            make.center.equalTo(arrow)
        }
    }
 
    private var scorllView:UIScrollView?
    private lazy var bgImage = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    private lazy var arrow = UIImageView(image:#imageLiteral(resourceName: "tableview_pull_refresh"))
    private lazy var lblTip = UILabel(title: "Hurry Up", fontsize: 14, textColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1))
    private lazy var activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    deinit {
        self.scorllView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
